package com.newworld.dmsapp2;

import java.io.File;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.newworld.dmsapp2.activity.MainActivity;
import com.newworld.dmsapp2.activity.serviceapply.WriteOutdoorPaperActivity;
import com.newworld.dmsapp2.bean.DataLevel;
import com.newworld.dmsapp2.bean.Function;
import com.newworld.dmsapp2.bean.Url;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.bean.UserAccount;
import com.newworld.dmsapp2.register.HouseProvingActivity;
import com.newworld.dmsapp2.register.UserMessageActivity;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.MyPreference;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.SysApplication;
import com.newworld.dmsapp2.util.Tool;

public class LoginActivity extends BaseActivity implements OnClickListener {
	private EditText login_edit_username, login_edit_password;
	private TextView login_tx_register, login_tx_forgetpsw;
	private AutoCompleteTextView ipedit;
	private Button login_btn_login;
	private ProgressBar progressbar;
	private Intent intent;
	private User user = new User();
	private String username = "";
	private String password = "";
	private String secretpassword = "";
	private Context context = this;
	public static final int NETWORK_UNAVAILABLE = 3;
	private String LOG = "LoginActivity";
	/*private List<String> hostIps = new ArrayList<String>();*/
	private List<Map<String,String>> hostIps = new ArrayList<Map<String, String>>();

	public static String IP_URL = "http://" + "219.140.198.82:18088/dms/";;
	// 获取只能被本应用程序读、写的SharedPreferences对象
	SharedPreferences preferences1;
	SharedPreferences.Editor editor1;
	private String[] items = { "219.140.198.82:18088/dms/",
			"219.140.198.82:18088/dms-1/", "59.69.101.18:8080/dms/",
			"10.139.46.238:8080/dms/", "10.139.12.103:8080/dms/",
			"10.139.59.233:8080/dms/", "10.139.48.35:8081/dms/" };
	private String message = "登录失败";
	private String flag;
	private String sessionId;
	private String currenthousetype = "residence";
	private boolean nonNetFlag = false;
	private RadioGroup rgHouseType;

	private CustomLoadingDialog uploadingdialog;

	public Handler progressBarHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Config.HANDLER_MSG_SUCCESS:
				showShortToast(message);
				if (null != progressbar)
					progressbar.setVisibility(View.VISIBLE);

				intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
				finish();
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				new Thread(getEditPersonRun).start();
				break;
			case Config.HANDLER_MSG_LOGIN_FAIL:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				if (null != progressbar)
					progressbar.setVisibility(View.INVISIBLE);

				Toast.makeText(LoginActivity.this, (String) msg.obj, Toast.LENGTH_SHORT)
						.show();

				break;
			case Config.HANDLER_MSG_LOGIN_FAIL_1:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				if (null != progressbar)
					progressbar.setVisibility(android.view.View.INVISIBLE);
				Toast.makeText(LoginActivity.this, "登录Ip出错", Toast.LENGTH_SHORT)
						.show();
				break;
			case Config.HANDLER_MSG_LOGIN_FAIL_2:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				progressbar.setVisibility(android.view.View.INVISIBLE);
				Toast.makeText(LoginActivity.this, "登录JSON解析出错",
						Toast.LENGTH_SHORT).show();
				break;
			case Config.HANDLER_MSG_LOGIN_FAIL_3:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				if(null != progressbar){
					progressbar.setVisibility(android.view.View.INVISIBLE);
				}
				System.out.println("联网登录出错" + "联网登录出错");
				Toast.makeText(LoginActivity.this, "联网登录出错", Toast.LENGTH_SHORT)
						.show();
				break;
			case 1:
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent);
				finish();
				break;
			case 2:
				hostIps = (List<Map<String,String>>) msg.obj;
				if (!nonNetFlag) {
					if (MyPreference.getInstance(LoginActivity.this)
							.getUserId() != 0) {
						User user = SingleSample
								.getInstance(LoginActivity.this).getUser();
						HandlerThread threadInternet = new HandlerThread(
								"internet_thread");
						threadInternet.start();
						Handler handlerInternet = new Handler(
								threadInternet.getLooper());// 替换默认循环，即用线程代替
						handlerInternet.post(runInternet);

					} else {
						setContentView(R.layout.activity_login);
						initViews();
						initEvents();
					}
				} else {

					HandlerThread threadInternet = new HandlerThread(
							"internet_thread");
					threadInternet.start();
					Handler handlerInternet = new Handler(
							threadInternet.getLooper());// 替换默认循环，即用线程代替
					handlerInternet.post(runInternet);
				}

				break;
			case NETWORK_UNAVAILABLE:
				if (null != progressbar)
					progressbar.setVisibility(View.INVISIBLE);
				Toast.makeText(LoginActivity.this, "请设置网络", Toast.LENGTH_SHORT)
						.show();
				break;
			case Config.HANDLER_MSG_GETEDITPERSON_SUCCESS:// 获取个人信息成功
				Intent intent0 = new Intent();
				intent0.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent0);
				finish();
				showShortToast((String) msg.obj);
				if (null != progressbar)
					progressbar.setVisibility(View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_GETEDITPERSON_FAIL:// 获取个人信息失败
				Intent intent1 = new Intent();
				intent1.setClass(getApplicationContext(), MainActivity.class);
				startActivity(intent1);
				finish();
				showShortToast((String) msg.obj);
				if (null != progressbar)
					progressbar.setVisibility(View.INVISIBLE);
				break;
			case Config.HANDLER_MSG_GETHOSTIP_FAIL:// 获取hostIp失败
				showShortToast((String) msg.obj);
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				if(null != progressbar){
					progressbar.setVisibility(android.view.View.INVISIBLE);
				}
				break;
			default:
				break;

			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		progressbar = (ProgressBar) findViewById(R.id.login_progressBar);
		// 加上以后可以一键关闭所有界面
		SysApplication.getInstance().addActivity(this);
		updateCodeAndSQL_Init();
		buildContent();
		// 如果已经登录过
		// 判断有无网络
		if (Tool.isNetworkAvailable(context)) {
			if (MyPreference.getInstance(LoginActivity.this).getUserId() != 0) {
				User user = SingleSample.getInstance(LoginActivity.this)
						.getUser();
				uploadingdialog = new CustomLoadingDialog(LoginActivity.this,
						"正在登录...");
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}
				new Thread(getHostIps).start();

			} else {
				nonNetFlag = true;
				setContentView(R.layout.activity_login);
				initViews();
				initEvents();
			}
		} else {
			setContentView(R.layout.activity_login);
			initViews();
			initEvents();
			showShortToast("请开启网络，重新登录");
			nonNetFlag = true;

		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	protected void initViews() {
		progressbar = (ProgressBar) findViewById(R.id.login_progressBar);
		login_edit_username = (EditText) findViewById(R.id.login_edit_username);
		login_edit_password = (EditText) findViewById(R.id.login_edit_password);
		login_btn_login = (Button) findViewById(R.id.login_btn_login);
		login_tx_register = (TextView) findViewById(R.id.login_tx_register);
		login_tx_forgetpsw = (TextView) findViewById(R.id.login_tx_forgetpsw);
		login_tx_forgetpsw.setVisibility(View.GONE);
		progressbar = (ProgressBar) findViewById(R.id.login_progressBar);
		ipedit = (AutoCompleteTextView) findViewById(R.id.login_ipeditAuto);
		rgHouseType = (RadioGroup)findViewById(R.id.radioGroup_housetype);
		rgHouseType.check(R.id.radioButton_residence); 
			
		rgHouseType.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup arg0, int arg1) {
				// TODO 自动生成的方法存根
				if(arg1 == R.id.radioButton_residence){
					currenthousetype  = "residence";
					login_tx_register.setVisibility(View.VISIBLE);
				}else{
					currenthousetype  = "business";
					login_tx_register.setVisibility(View.GONE);
				}
			}
		});
		ipedit.setVisibility(View.GONE);// 发版隐藏
		preferences1 = getSharedPreferences("dmsip", MODE_WORLD_READABLE);
		editor1 = preferences1.edit();
		if (null != preferences1
				&& !preferences1.getString("ip", "").equals("")) {
			ipedit.setText(preferences1.getString("ip", ""));
		} else {
			ipedit.setText(items[0]);
		}
		IP_URL = "http://" + ipedit.getText().toString();
		// 步骤1：设置适配器
		ipedit.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, items));

	}

	@Override
	protected void initEvents() {
		login_edit_username.setOnClickListener(this);
		login_edit_password.setOnClickListener(this);
		login_btn_login.setOnClickListener(this);
		login_tx_register.setOnClickListener(this);
		login_tx_register.setVisibility(View.VISIBLE);
		login_tx_forgetpsw.setOnClickListener(this);
		

		// new Thread(runsetData).start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn_login:

			// 判断有无网络
			if (Tool.isNetworkAvailable(context)) {

				if (null != progressbar) {
					progressbar.setVisibility(android.view.View.VISIBLE);
				}
				logIn();
			} else {
				nonNetFlag = true;
				showShortToast("请开启网络");
			}

			// logIn();
			break;
		case R.id.login_tx_register:
			showLongToast("注册");
			UserMessageActivity.INTENT_FLAG = 0;
			WriteOutdoorPaperActivity.PUBLIC_FLAG = false;
			intentActivity(context, HouseProvingActivity.class);
			break;
		case R.id.login_tx_forgetpsw:
			showLongToast("忘记密码");
			break;
		default:
			break;
		}
	}

	/**
	 * 监听Back键按下事件,方法2: 注意: 返回值表示:是否能完全处理该事件 在此处返回false,所以会继续传播该事件.
	 * 在具体项目中此处的返回值视情况而定.
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			// 关闭整个程序
			SysApplication.getInstance().exit();

			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	}

	/**
	 * 根据versioncode判断软件是不是更新过，如果软件更新过，需要重新获取standard
	 */
	private void updateCodeAndSQL_Init() {
		PackageManager packageManager = getPackageManager();
		// getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo;
		try {
			packInfo = packageManager.getPackageInfo(getPackageName(), 0);
			int code = packInfo.versionCode;
			if (code != MyPreference.getInstance(this).getVersionCode()) {
				MyPreference.getInstance(this).setSqlInit(false);
				MyPreference.getInstance(this).setVersionCode(code);
			}
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 
	 * 点击登录
	 * 
	 * @param view
	 */
	public void logIn() {
		username = login_edit_username.getText().toString();
		password = login_edit_username.getText().toString();

		IP_URL = "http://" + ipedit.getText().toString();
		editor1.putString("ip", ipedit.getText().toString());
		// 提交所有存入的数据
		editor1.commit();

		if (username.length() == 0 || password.length() == 0) {
			showShortToast("用户名和密码不能为空");
		} else {
			// 联网登陆子线程 3.加注销按钮，轻量级 xml表 set user_id=0
			// 判断有无网络
			if (Tool.isNetworkAvailable(context)) {
				if (!nonNetFlag) {
					HandlerThread threadInternet = new HandlerThread(
							"internet_thread");
					threadInternet.start();
					Handler handlerInternet = new Handler(
							threadInternet.getLooper());// 替换默认循环，即用线程代替
					handlerInternet.post(runInternet);
					if (null != progressbar) {
						progressbar.setVisibility(android.view.View.VISIBLE);
					}
				} else {
					uploadingdialog = new CustomLoadingDialog(
							LoginActivity.this, "正在登录...");
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
					new Thread(getHostIps).start();
				}
			} else {
				showShortToast("请开启网络");
			}

		}
	}

	/**
	 * 联网登录
	 */

	Runnable runInternet = new Runnable() {
		@Override
		public void run() {
			if (MyPreference.getInstance(LoginActivity.this).getUserId() != 0) {
				User user = SingleSample.getInstance(LoginActivity.this)
						.getUser();
				username = user.getUsername();
				password = user.getPassword();
				secretpassword = encryption(password);
				Log.e("secretpassword11", secretpassword);
				List<User> userList = DataSupport.where(
						"username = ? and password = ?", username, password)
						.find(User.class);
				// 判断有无网络
				if (Tool.isNetworkAvailable(context)) {

					User u = post(username, secretpassword);
					user.deleteAllFunction();
					user.setSessionId(sessionId);
					List<Function> functions;
					if (null != u) {
						functions = u.getFunctions();
						for (Function function : functions) {
							function.setUser(user);
						}
						DataSupport.saveAll(functions);
						user.setFunctions(functions);
					}

					user.update(user.getId());
					user.updateAll("username = ? and password = ?", username,
							password);
					MyPreference.getInstance(context).setUserId(user.getId());
					SingleSample.resetInstance();

					progressBarHandler
							.sendEmptyMessage(Config.HANDLER_MSG_SUCCESS);
				} else {
					progressBarHandler.sendEmptyMessage(NETWORK_UNAVAILABLE);

				}

			} else {
				username = login_edit_username.getText().toString();
				password = login_edit_password.getText().toString();
				secretpassword = encryption(password);
				Log.e("secretpassword22", secretpassword);
				User user = new User();
				List<User> userList = DataSupport.where(
						"username = ? and password = ?", username, password)
						.find(User.class);
				// 判断有无网络
				if (Tool.isNetworkAvailable(context)) {
					User u = post(username, secretpassword);

					if (null == u || u.getFlag() == null || u.getFlag().equals("false")) {
						progressBarHandler.obtainMessage(
								Config.HANDLER_MSG_LOGIN_FAIL, message)
								.sendToTarget();

					} else {

						if (userList.size() == 0) {
							user.setUsername(username);
							user.setPassword(password);
							user.setSessionId(sessionId);
							user.save();
							user.deleteAllFunction();
							List<Function> functions = u.getFunctions();
							for (Function function : functions) {
								function.setUser(user);
								function.save();
							}
							u.setFunctions(functions);
							u.update(user.getId());
							if (user.isSaved()) {
								MyPreference.getInstance(context).setUserId(
										user.getId());
								MyPreference.getInstance(context)
										.setRefreshState(true);
								SingleSample.resetInstance();
								progressBarHandler
										.sendEmptyMessage(Config.HANDLER_MSG_SUCCESS);
							} else {
								progressBarHandler
										.sendEmptyMessage(Config.HANDLER_MSG_FAIL);
							}
						} else {
							// TODO
							user.updateAll();
							user.deleteAllFunction();
							user = userList.get(0);
							user.setSessionId(sessionId);
							List<Function> functions = u.getFunctions();
							for (Function function : functions) {
								function.setUser(user);
								function.save();
							}
							user.setFunctions(functions);
							user.update(user.getId());
							MyPreference.getInstance(context).setUserId(
									user.getId());
							SingleSample.resetInstance();
							// 转到主界面
							Intent intent = new Intent();
							intent.setClass(getApplicationContext(),
									MainActivity.class);
							startActivity(intent);
							finish();
						}
					}
				} else {

					progressBarHandler.sendEmptyMessage(NETWORK_UNAVAILABLE);

				}
			}

		}
	};

	@Override
	public void onDestroy() {
		progressbar = null;
		progressBarHandler = null;
		Log.e(LOG, "onDestroy");
		SysApplication.getInstance().rmActivity(this);
		super.onDestroy();
	}

	// 定义发送请求的方法
	public User post(String username, String password) {

		// 使用Map封装请求参数
		Map<String, String> map = new HashMap<String, String>();

		// 二期
		map.put("userName", username);
		map.put("password", password);
		map.put("client", "android");
		String setsessionid = "";
		user = SingleSample.getInstance(LoginActivity.this).getUser();
		if (null != user) {
			if (null != user.getSessionId() && !user.getSessionId().equals("")) {
				setsessionid = user.getSessionId();
			}
		}        
		// 定义发送请求的URL
		// 发送请求
		String response = "";
		User getuser = new User();
		String realip ="";
		List<String>logincode = new ArrayList<String>();
		List<String>loginip = new ArrayList<String>();
		for(int i=0; i <  hostIps.size() ;i++){
			logincode.add(hostIps.get(i).get("code"));
			loginip.add(hostIps.get(i).get("value"));
		}
		for (int j=0; j< logincode.size(); j++) {
			String code = logincode.get(j);
			String ip = loginip.get(j);
			//realip = Tool.judgeHouseType(currenthousetype,code,ip);
			//Log.e("currenthousetype+code+ip+realip", currenthousetype+"  "+code+"  "+ip+"  "+realip);
			/*if(!realip.equals("")){*/
				try {
					Config.SERVER_URL = "http://10.139.4.177:8080/dpms/";
					realip = Config.SERVER_URL;
					Log.e("登录列表realip", realip);
					
					Log.e("Config.SERVER_URL", Config.SERVER_URL);
					response = HttpUtil.loginpostRequestSes(realip
							+ "loginController.do?login", map, setsessionid);
					Log.e("post", response);
					if (!response.equals(Config.HTTP_FAIL)) {
						if (null != response && !response.equals("")) {
							MyPreference.getInstance(context).setServerUrl(realip);
							// user.setIp(ip);
							Log.e("登录realip", realip);
							Log.e("登录response", response);
							message = new JSONObject(response).getString("message");
							System.out.println("message----1" + message);
							flag = new JSONObject(response).getString("flag");
							System.out.println("flag----1" + flag);
							if (flag.equals(Config.CONNECT_SUCCESS)) {
								sessionId = HttpUtil.getsessionId();
								// ----?
								java.lang.reflect.Type type = new TypeToken<User>() {
								}.getType();
								Gson gson = new Gson();
								getuser = gson.fromJson(response, type);
								return getuser;
							} else {
								/*
								 * progressBarHandler.obtainMessage(
								 * Config.HANDLER_MSG_LOGIN_FAIL, message)
								 * .sendToTarget();
								 */
							}
							showLogDebug(LOG, response);
							showLogDebug(LOG, message);
							break;
						} else {
							progressBarHandler.obtainMessage(
									Config.HANDLER_MSG_LOGIN_FAIL_1, "登录IP出错")
									.sendToTarget();
						}
					} else {
						progressBarHandler.obtainMessage(
								Config.HANDLER_MSG_LOGIN_FAIL_1, Config.HTTP_FAIL)
								.sendToTarget();
					}

				} catch (JsonSyntaxException e) {
					progressBarHandler.obtainMessage(
							Config.HANDLER_MSG_LOGIN_FAIL_2, "登录JSON解析出错")
							.sendToTarget();
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
					progressBarHandler.obtainMessage(
							Config.HANDLER_MSG_LOGIN_FAIL_3, "联网登录出错")
							.sendToTarget();
				}
			/*}else{
				Toast.makeText(this, "匹配ip失败", Toast.LENGTH_SHORT);
			}
		}	*/
		
		}

		return getuser;
	}

	Runnable runsetData = new Runnable() {
		@Override
		public void run() {
			setDatalevel();
		}
	};

	private void setDatalevel() {
		DataLevel datalevel = new DataLevel();
		datalevel.DataLevel("135645456456131321564561", "TSNation", "国家级", "");
		datalevel.save();
		datalevel.DataLevel("135645456456131321564562", "TSProvince", "省级", "");
		datalevel.save();
		datalevel.DataLevel("135645456456131321564563", "TSCity", "市级", "");
		datalevel.save();
		datalevel.DataLevel("135645456456131321564564", "TSPhase", "期级", "");
		datalevel.save();
		datalevel.DataLevel("135645456456131321564566", "TSBlock", "栋级", "");
		datalevel.save();
	}

	Runnable getHostIps = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			List<Map<String,String>> hostIps = new ArrayList<Map<String, String>>();
			String setsessionid = "";
			user = SingleSample.getInstance(LoginActivity.this).getUser();
			if (null != user) {
				if (null != user.getSessionId()
						&& !user.getSessionId().equals("")) {
					setsessionid = user.getSessionId();
				}
			}
			try {
				Config.SERVER_URL = "http://59.69.101.18:6999/dpms/";
				String result = HttpUtil.postRequestNomapSe(Tool.getConfigUrl(Config.SERVER_URL, Config.GETHOST_URL),
						setsessionid);
				Log.e("Login-->Config.SERVER_URL",Config.SERVER_URL);
				Log.e("获取hostIp的result", result);
				if (!result.equals(Config.HTTP_FAIL)) {
					JSONObject jsonobj = new JSONObject(result);
					//String message = jsonobj.getString("message");
					if (jsonobj.getString("success").equals("true")) {
						/*String rows = jsonobj.getString("mainHostAddress");
						java.lang.reflect.Type type = new TypeToken<HostAdress>() {
						}.getType();
						Gson gson = new Gson();
						HostAdress HostAdress = gson.fromJson(rows, type);
						for (Url u : HostAdress.getMainHostAddress()) {
							hostIps.add(u.getValue());
							Log.e("android访问主机地址", u.getName() + u.getValue());
						}*/
						String rows = jsonobj.getString("mainHostAddress");
						java.lang.reflect.Type type = new TypeToken<List<Url>>() {
						}.getType();
						Gson gson = new Gson();
						List<Url> urlList = gson.fromJson(rows, type);
						for (Url u : urlList) {
							Map<String,String>map1 = new HashMap<String, String>();
							map1.put("value",u.getValue());
							map1.put("code",u.getCode());
							hostIps.add(map1);
							Log.e("android访问主机地址", u.getName() + u.getValue()+u.getCode());
						}
						progressBarHandler.obtainMessage(2, hostIps)
								.sendToTarget();// 通知主线程数据发送成功
					} else {
						Log.e("获取hostIp的result", message);
						progressBarHandler.obtainMessage(
								Config.HANDLER_MSG_GETHOSTIP_FAIL, message)
								.sendToTarget();// 通知主线程数据发送成功
					}
				} else {
					Log.e("获取hostIp的result", result);
					progressBarHandler.obtainMessage(
							Config.HANDLER_MSG_GETHOSTIP_FAIL,
							"获取服务器地址失败,请重启APP").sendToTarget();// 通知主线程数据发送成功
				}

			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				progressBarHandler.obtainMessage(
						Config.HANDLER_MSG_GETHOSTIP_FAIL, "获取服务器地址失败")
						.sendToTarget();// 通知主线程数据发送成功
			}

		}
	};

	// 获取个人信息
	Runnable getEditPersonRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			getEditPerson();
		}
	};

	// 获取个人信息
	private void getEditPerson() {

		try {
			String setsessionid = "";
			user = SingleSample.getInstance(LoginActivity.this).getUser();
			if (null != user) {
				if (null != user.getSessionId()
						&& !user.getSessionId().equals("")) {
					setsessionid = user.getSessionId();
				}
			}
			String url = Tool.getConfigUrl(Config.SERVER_URL, Config.GET_PERSON_URL);
			//String url = "userController.do?viewPersonInf";
			String result = null;
			result = HttpUtil.postRequestNomapSe(url, setsessionid);
			Log.e("获取个人信息的result", result);
			if (!result.equals(Config.HTTP_FAIL)) {
				result = result.replace("rows", "useraccounts");
				JSONObject jsonobj = new JSONObject(result);
				String message = jsonobj.getString("message");
				String flag = jsonobj.getString("flag");
				String rows = jsonobj.getString("useraccounts");
				rows = rows.replace("id", "userId");
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					java.lang.reflect.Type type = new TypeToken<List<UserAccount>>() {
					}.getType();
					Gson gson = new Gson();
					List<UserAccount> uas = gson.fromJson(rows, type);
					if (!user.getUseraccounts().isEmpty()) {
						DataSupport.deleteAll(UserAccount.class);
					}
					String userid = "";
					for (UserAccount ua : uas) {
						ua.setUser(user);
						ua.save();
						userid = ua.getUserId();
					}
					user.setUserId(userid);
					user.setUseraccounts(uas);
					user.update(user.getId());

				} else {
					List<UserAccount> us = new ArrayList<UserAccount>();
					UserAccount ua = new UserAccount();
					ua.setUser(user);
					ua.save();
					us.add(ua);
					user.setUseraccounts(us);
					user.update(user.getId());
					progressBarHandler.obtainMessage(
							Config.HANDLER_MSG_GETEDITPERSON_FAIL, message)
							.sendToTarget();// 通知主线程数据发送失败
				}
			} else {
				List<UserAccount> us = new ArrayList<UserAccount>();
				UserAccount ua = new UserAccount();
				ua.setUser(user);
				ua.save();
				us.add(ua);
				user.setUseraccounts(us);
				user.update(user.getId());
				progressBarHandler
						.obtainMessage(Config.HANDLER_MSG_GETEDITPERSON_FAIL,
								Config.HTTP_FAIL).sendToTarget();// 通知主线程数据发送失败
			}

		} catch (Exception e) {

			Log.e("ServiceScheduleActivity", "个人信息数据获取报错");

			progressBarHandler.obtainMessage(
					Config.HANDLER_MSG_GETEDITPERSON_FAIL, "个人信息数据获取报错")
					.sendToTarget();// 通知主线程数据发送失败
			e.printStackTrace();
		}
	}

	// 创建文件夹
	private void buildContent() {
		File downdestDir = new File(Environment.getExternalStorageDirectory()
				.getPath() + File.separator + "NewWorld_APP2_AvatarImage");
		if (!downdestDir.exists()) {
			downdestDir.mkdirs();
		}
		File imagedestDir = new File(Environment.getExternalStorageDirectory()
				.getPath() + File.separator + "NewWorld_APP2_Photo");
		if (!imagedestDir.exists()) {
			imagedestDir.mkdirs();
		}

		File voicedestDir = new File(Environment.getExternalStorageDirectory()
				.getPath() + File.separator + "NewWorld_APP2_Voice");
		if (!voicedestDir.exists()) {
			voicedestDir.mkdirs();
		}

		File txtdestDir = new File(Environment.getExternalStorageDirectory()
				.getPath() + File.separator + "NewWorld_APP2_Software");
		if (!txtdestDir.exists()) {
			txtdestDir.mkdirs();
		}

	}
	//密码加密
	public static String encryption(String plainText) {
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
 
            int i;
 
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
 
            re_md5 = buf.toString();
 
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }


}
